import Database from 'better-sqlite3';

interface AuthInfo {
    email: string;
    accessToken: string;
}

/**
 * Injects authentication information into the state.vscdb SQLite database.
 * This function strictly follows the logic of the provided Python script.
 * @param dbPath - The full path to the state.vscdb file.
 * @param authInfo - An object containing the email and access token to inject.
 * @returns An object indicating success or failure.
 */
export async function injectAuthInfo(dbPath: string, authInfo: AuthInfo): Promise<{ success: boolean; message: string }> {
    try {
        // Connect to the database, creating it if it doesn't exist.
        const db = new Database(dbPath);

        // Apply PRAGMA settings for performance, as seen in the Python script.
        db.pragma('busy_timeout = 5000');
        db.pragma('journal_mode = WAL');
        db.pragma('synchronous = NORMAL');
        
        // Ensure the target table exists.
        db.exec(`
            CREATE TABLE IF NOT EXISTS "ItemTable" (
                "key" TEXT NOT NULL UNIQUE,
                "value" TEXT,
                PRIMARY KEY("key")
            )
        `);

        // Use a prepared statement for efficient insertion/replacement.
        const stmt = db.prepare('INSERT OR REPLACE INTO ItemTable (key, value) VALUES (?, ?)');

        // The Python script uses a transaction, which is a best practice.
        const injectTransaction = db.transaction((items: { key: string; value: string }[]) => {
            for (const item of items) {
                stmt.run(item.key, item.value);
            }
        });
        
        const itemsToUpdate = [
            { key: 'cursorAuth/cachedSignUpType', value: 'Auth_0' },
            { key: 'cursorAuth/cachedEmail', value: authInfo.email },
            { key: 'cursorAuth/accessToken', value: authInfo.accessToken },
        ];

        // Execute the transaction.
        injectTransaction(itemsToUpdate);

        db.close();
        
        return { success: true, message: '账号信息已成功注入。' };
    } catch (error: unknown) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        console.error(`Failed to inject auth info into SQLite database at ${dbPath}:`, error);
        return { success: false, message: `注入账号信息失败: ${errorMessage}` };
    }
}
